<?php
/**
 * Created By   : robertwilson
 * Date         : 5/4/13
 * Time         : 1:14 PM
 * File         : Database.php
 * Class        : Database
 */

require_once 'Session.php';
function pr($data)
{
    echo '<pre>';
    print_r($data);
}

class Database
{

    const USER = 'root';
    const HOST = 'localhost';
    const PASS = 'dev123';
    const DB = 'assessmentdb';


    private $connection = false;

    public function __construct()
    {
        $this->connection = mysql_connect(self::HOST, self::USER, self::PASS);
        if (!$this->connection) {
            exit('NO DATABASE CONNECTION FOUND');
        }
        mysql_select_db(self::DB);
        $this->init();
    }

    public function init()
    {
        if (isset($_POST['login'])) {
            $foundUser = $this->auth($_POST['username'], $_POST['password']);
            if (is_object($foundUser)) {
                Session::set('sessionToken', $foundUser->username);
                Session::set('sid', $foundUser->id);
                Session::set('email', $foundUser->email);
                header('Location: pages/dashboard.php');
                exit;
            }

        }

        if (isset($_GET['logout'])) {
            Session::clearSession();
        }

        if (isset($_POST['create'])) {

            $errors = $this->validate($_POST);
            if (empty($errors)) {
                unset($_POST['create']);
                $this->save('assessment', $_POST);
            }
        }

        if (isset($_POST['changeStatus'])) {

            $table = $_POST['table'];
            $id = $_POST['id'];
            $status = array('status' => $_POST['status'] == 1 ? 0 : 1);

            $result = $this->update($table, $id, $status);
            if (is_array($result)) {
                $result['status'] = $_POST['status'] == 1 ? 0 : 1;
                echo json_encode($result);
                exit;
            }
        }

        if (isset($_POST['register'])) {
            unset($_POST['register']);

            $password = $_POST['password'];
            $confirmPassword = $_POST['confirm_password'];

            if ($password === $confirmPassword) {
                unset($_POST['confirm_password']);
                $_POST['password'] = hash('sha1', $password);

                if ($this->save('users', $_POST)) {
                    header('Location: index.php');
                    exit;
                }
            }
            else {
                exit('Password Mismatch. <a href="register.php">Go Back</a>');
            }

            pr($_POST);

        }
    }

    public function save($table = null, array $data)
    {
        $keys = array_keys($data);
        $values = array_values($data);

        $preparedValues = function($v) {
            return "'" . mysql_real_escape_string($v) . "',";
        };
        $cleanedValues = array_map($preparedValues, $values);

        $sql = "INSERT INTO {$table} (" . implode(",", $keys);
        $sql .= ") VALUE ( " . rtrim(implode($cleanedValues), ',') . ")";
        mysql_query($sql);
        if (mysql_affected_rows() == 1) {
            return mysql_insert_id();
        }
        else {
            return false;
        }

    }

    public function insert($table = null, array $data)
    {

    }

    public function find($table = null)
    {
        $sql = "SELECT * FROM {$table}";
        $result = mysql_query($sql, $this->connection);

        return mysql_num_rows($result) > 0 ? $result : false;
    }

    public function auth($username = '', $password = '')
    {
        if (!empty($username) && !empty($password)) {
            $sql = 'SELECT * FROM users WHERE username = \'' . mysql_real_escape_string($username);
            $sql .= '\' AND password = \'' . mysql_real_escape_string(hash('sha1', $password)) . '\'';

            //var_dump($sql); exit;
            $result = mysql_query($sql, $this->connection);

            if (mysql_num_rows($result) == 1) {
                return mysql_fetch_object($result);
            }
            else {
                return false;
            }
        }
    }

    public function findById($table = null, $id = 0)
    {
        if (!is_null($table) && (is_numeric($id) && $id > 0)) {
            $sql = "SELECT * FROM {$table} WHERE id = " . mysql_real_escape_string(intval($id));
            $result = mysql_query($sql, $this->connection);
            if (mysql_num_rows($result) == 1) {
                return mysql_fetch_object($result);
            }
            else {
                return false;
            }
        }
    }

    public function findRelation($table = null, $field = null, $id = 0)
    {
        if (!is_null($table) && (is_numeric($id) && $id > 0) && !is_null($field)) {
            $sql = "SELECT * FROM {$table} WHERE " . mysql_real_escape_string($field) . " = " . mysql_real_escape_string(intval($id));
            $result = mysql_query($sql, $this->connection);

            return mysql_num_rows($result) > 0 ? $result : false;
        }
    }

    public function update($table = null, $id = null, $data = null)
    {
        if (!is_null($table) && is_numeric($id) && is_array($data)) {
            $preparedValues = '';
            foreach ($data as $key => $value) {
                $preparedValues .= $key . " = '" . mysql_real_escape_string($value) . "',";
            }

            $sql = "UPDATE {$table} SET " . rtrim($preparedValues, ',');
            $sql .= " WHERE id = " . mysql_real_escape_string(intval($id));

            mysql_query($sql);
            if (mysql_affected_rows() == 1) {
                return array('update' => 'true');
            } else {
                return false;
            }

        } else {
           return false;
        }
    }

    private function validate(array $data)
    {
        $error = array();

        if (is_array($data)) {
            foreach ($data as $key => $value) {
                if (empty($value)) {
                    $error[$key] = ucfirst($key) . " can't be empty";
                }
            }
        }

        return $error;
    }
}
